package com.cetccst.securitysuite.network;

import android.text.TextUtils;

import com.cetccst.securitysuite.log.SSLogger;
import com.cetccst.securitysuite.network.respone.BaseResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class HttpCallback<T> implements Callback<T> {

    private static final String TAG = "HttpCallback";
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response != null) {
            SSLogger.logger.info("response:" + response.toString());
            if (response.body() instanceof BaseResponse) {//对于资源下载，不做处理
                int errorCode = ((BaseResponse) response.body()).getErrCode();
                //errorCode处理
                switch (errorCode) {
                    case 10000://token过期
                        //TODO 处理token过期
                    break;
                    default:
                        String errorMsg = HttpErrorMap.getErrorMap().get(errorCode);
                        if (!TextUtils.isEmpty(errorMsg)) {
                            ((BaseResponse) response.body()).setErrMessage(errorMsg);
                        }
                        break;
                }
            }

        }
        onResponse(response != null ? response.body() : null);
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        SSLogger.logger.error(call.request().toString(), t);
        if (call.isCanceled()) {
            return;
        }
        //此时调用正常返回，传递null
        onResponse(call, null);
    }

    public abstract void onResponse(T data);
}
